import axios, { type Method } from 'axios'
// import { message } from '@/utils/AntdGlobal'
import { useSysConfigStore } from '@/stores/config'
import { useUserStore } from '@/stores/user'
import router from '@/router'
import { message } from '@/utils/AntdGlobal'

const service = axios.create({
  baseURL: '/api',
  timeout: 1000 * 60 * 10
})

service.interceptors.request.use((config) => {
  const defaultLanguage = useSysConfigStore.getState().defaultLanguage
  const token = useUserStore.getState().token
  config.headers['Accept-Language'] = defaultLanguage
  if (token)
    config.headers.token = token
  return config
}, (error) => {
  return Promise.reject(error)
})
service.interceptors.response.use((response) => {
  if (response.data.code === 400401) {
    useUserStore.setState({ token: '' })
    router.navigate('/login', { replace: true })
    return
  }
  if (response.data.code === 0) {
    message.error(response.data.msg)
  }
  return response.data
}, (err) => {
  if (err.response.status === 401) {
    message.error("暂时无权限失败")
    // 跳转登录，带上接口失效所在页面的地址，登录完成后回跳使用
    // router.navigate('/login')
  }
  return Promise.reject(err)
})

// function request<T = any>(config: AxiosRequestConfig<T>): Promise<T> {
//   return new Promise((resolve, reject) => {
//     service.request<any, T>(config).then((res: any) => {
//       if (res.code !== 1) {
//         message.error(res.msg)
//         return reject(res)
//       }
//       resolve(res.data)
//     }).catch((err) => {
//       return reject(err)
//     })
//   })
// }

// export function get<T = any>(url: string, config?: AxiosRequestConfig<T>): Promise<T> {
//   return request<T>({ ...config, method: 'GET', url })
// }

// export function post<T = any>(url: string, config?: AxiosRequestConfig<T>): Promise<T> {
//   return request<T>({ ...config, method: 'POST', url })
// }

// export function put<T = any>(url: string, config?: AxiosRequestConfig<T>): Promise<T> {
//   return request<T>({ ...config, method: 'PUT', url })
// }

// export function del<T = any>(url: string, config?: AxiosRequestConfig<T>): Promise<T> {
//   return request<T>({ ...config, method: 'Delete', url })
// }
type Data<T> = {
  code: number
  msg: string
  data: T
}
// 4. 请求工具函数
const request = <T>(url: string, method: Method = 'get', submitData?: object, flag?: Boolean) => {
  return service.request<T, Data<T>>({
    url,
    method,
    [method.toLowerCase() === 'get' || method.toLowerCase() === 'delete' ? 'params' : method.toLowerCase() === 'post' && flag ? 'params' : 'data']: submitData
  })
}

export { request }
